import json
import re
from random import randint

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.user.models import User
from utils.sms.sms_util import SmsUtil


class SmsCodeView(View):
    def post(self, request):
        mobile = request.POST.get('mobile')

        if not mobile:
            return JsonResponse({"code": 401, "errmsg": "参数错误"})
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', mobile):
            return JsonResponse({"code": 401, "errmsg": "手机号码不正确"})

        user = User.objects.filter(mobile=mobile)
        if user:
            return JsonResponse({"code": 401, "errmsg": "该手机号已注册，直接登录或忘记密码"})
        # 连接redis
        redis_cli = get_redis_connection('code')
        # 存到redis一个变量180秒如果存在就返回操作过于频繁， 避免频繁发送验证码
        send_flag = redis_cli.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 402, 'errmsg': '操作过于频繁'})

        # 创建redis管道， 节省时间
        pl = redis_cli.pipeline()
        # 获取一个6位数短信验证码
        sms_code = '%06d' % randint(0, 999999)

        # 存入验证频繁的变量和短信验证码到redis数据库
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex('sms_%s' % mobile, 120, sms_code)
        # 执行操作
        pl.execute()
        # 发送短信到用户手机，三分钟有效期
        # SmsUtil().send_message('1', mobile, (sms_code, '3'))
        SmsUtil().send_message('1', mobile, (sms_code, '2'))
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


